
pub mod alias_dict;
pub mod full_config;

use full_config::FullConfig;

pub fn read_from_toml(toml_file_path: &str) -> FullConfig {
  let toml_content = std::fs::read_to_string(toml_file_path).expect(
    format!("read file error: [{}]", toml_file_path).as_str()
  );
  toml::from_str::<FullConfig>(&toml_content).expect(
    format!("parse file error: [{}]", toml_file_path).as_str()
  )
}

pub fn get_cmd_and_work_directory(
  cmd_id: &str
) -> (String, String) {
  let path_name_list = crate::path_util::get_config_toml_path_name_list();
  let mut target_cmd = String::new();
  let mut work_directory = crate::path_util::path_buf_to_string(crate::path_util::get_current_dir());
  path_name_list.iter().find(|path_name| {
      let config_name = path_name.as_str();
      let config_dict = read_from_toml(config_name);
      let target_alias = config_dict.find_target(cmd_id);
      if target_alias.is_some() {
          let target_one = target_alias.unwrap();
          target_cmd = target_one.cmd;
          if target_one.work_directory.is_some() {
              work_directory = target_one.work_directory.unwrap();
          }
          return true;
      }
      return false;
  });
  if target_cmd.is_empty() {
    println!("cannot found target command");    
  }
  (target_cmd, work_directory)
}

pub fn get_cmd_and_work_directory_from(cmd_id: &str, config_list: &Vec<FullConfig>) -> (String, String) {
  let mut target_cmd = String::new();
  let mut work_directory = crate::path_util::path_buf_to_string(crate::path_util::get_current_dir());
  config_list.iter().find(|config_one|{
    let target_alias = config_one.find_target(cmd_id);
    if target_alias.is_some() {
      let target_one = target_alias.unwrap();
      target_cmd = target_one.cmd;
      if target_one.work_directory.is_some() {
        work_directory = target_one.work_directory.unwrap();
      }
      return true;
    }
    return false;
  });
  if target_cmd.is_empty() {
    println!("cannot found target command: [{}]", cmd_id);    
  }
  (target_cmd, work_directory)
}
